﻿using System;
using System.Collections.Generic;
using System.Linq;
using Api.Model;
using Articles = System.Collections.Generic.IEnumerable<Api.Model.Article>;
using Tags = System.Collections.Generic.IEnumerable<Api.Model.Tag>;

namespace Core.Model
{
    public class ArticlesModel : IArticlesModel
    {
        private List<Article> articles = new List<Article>();
        private List<Tag> tags = new List<Tag>();

        public Articles GetArticles()
        {
            if (AreArticlesLoaded)
            {
                return articles;
            }
            else
            {
                throw new InvalidOperationException("Call addArticles first");
            }      
        }

        public void AddArticles(Articles articles)
        {
            if (articles == null)
            {
                throw new ArgumentNullException("articles");
            }

            if (articles.Count() == 0)
            {
                throw new ArgumentException("articles empty");
            }

            this.articles.AddRange(articles);
            UpdateTags();
        }

        private void UpdateTags()
        {
            var allTags = this.articles.Where(article => article.Tags != null)
                                       .SelectMany(article => article.Tags).ToList();

            this.tags = allTags.Distinct().ToList();
        }

        public Tags GetTags()
        {
            if (!AreArticlesLoaded || !AreTagsAvailable)
            {
                throw new InvalidOperationException("Call addArticles first");
            }

            return tags;
        }

        public bool AreArticlesLoaded
        {
            get 
            {
                return articles.Count > 0;
            }
        }

        public bool AreTagsAvailable
        {
            get 
            {
                return tags.Count > 0;
            }
        }
    }
}
